package com.mlink.ai.chat.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.mlink.ai.chat.assistant.robot.databinding.ItemChatHistoryBinding
import com.mlink.ai.chat.local.entity.ChatMessageEntity

class ChatHistoryRecyclerAdapter :
    ListAdapter<ChatMessageEntity, ChatHistoryRecyclerAdapter.HistoryViewHolder>(HistoryDiffCallback()) {

    var onMessageDelete: ((ChatMessageEntity) -> Unit)? = null
    var onMessageClick: ((ChatMessageEntity) -> Unit)? = null
    var onDeleteShow: ((View) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
        return HistoryViewHolder(
            ItemChatHistoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        val item = getItem(position)
        holder.binding.run {
            tvDate.text = item.date
            tvTitle.text = item.messageTitle
            rlDelete.isVisible = false

            ivDelete.setOnClickListener {
                onDeleteShow?.invoke(rlDelete)
                rlDelete.isVisible = true
            }

            ivYes.setOnClickListener {
                onMessageDelete?.invoke(item)
                rlDelete.isVisible = false
            }

            ivNo.setOnClickListener {
                rlDelete.isVisible = false
            }

            root.setOnClickListener {
                onMessageClick?.invoke(item)
            }
        }

    }

    inner class HistoryViewHolder(val binding: ItemChatHistoryBinding) :
        RecyclerView.ViewHolder(binding.root)

    class HistoryDiffCallback : DiffUtil.ItemCallback<ChatMessageEntity>() {
        override fun areItemsTheSame(
            oldItem: ChatMessageEntity,
            newItem: ChatMessageEntity
        ): Boolean {
            return oldItem.messageId == newItem.messageId
        }

        override fun areContentsTheSame(
            oldItem: ChatMessageEntity,
            newItem: ChatMessageEntity
        ): Boolean {
            return oldItem.messageId == newItem.messageId
        }

    }
}